package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Cacheable(value = "dict",keyGenerator = "keyGenerator")  //将返回数据放到缓存中
    @Override
    public List<Dict> findChildData(Long id) {

        //继承ServiceImpl<DictMapper, Dict>，这里面已经自动引入了Mapper，所以不需要@Autowird
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id",id);
        List<Dict> dicts = baseMapper.selectList(dictQueryWrapper);
        //向list集合对象中设置hasChildren值，因为这个值数据库中没有
        //大数据量下如此频繁查询数据库会对数据库造成很大的负担，这个有没有可能整合到缓存数据中去呢？
        for (Dict dict : dicts){
            boolean hasChildren = this.hasChildren(dict.getId());
            if(hasChildren){
                dict.setHasChildren(true);
            }else{
                dict.setHasChildren(false);
            }
        }
        return dicts;
    }

    //导出数据字典信息
    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        List<Dict> dicts = baseMapper.selectList(null);

        //将dict转换成DictEeVo对象，因为doWrite写的是DictEeVo对象
        List<DictEeVo> voList = new ArrayList<>();
        for (Dict dict: dicts) {
            DictEeVo dictEeVo = new DictEeVo();

            //BeanUtils.copyProperties实现对象的复制
            //dictEeVo.setId(dict.getId());
            BeanUtils.copyProperties(dict,dictEeVo);  //这个好像需要两个类中的属性名相同才会做复制操作
            voList.add(dictEeVo);
        }

        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(voList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //导入数据字典信息
    @CacheEvict(value = "dict", allEntries=true)  //此方法调用时清空dict缓存
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(dictMapper))
                    .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //根据dictCode和value来查询dict
    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，则直接根据value查询
        if(StringUtils.isEmpty(dictCode)){
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else{
            //不为空，现根据dictcode查询dict对象获取其id值
            /*QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("dict_code",dictCode);*/
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long parentId = codeDict.getId();
            //实际是根据parentid和value来进行查询
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id",parentId).eq("value",value);
            return baseMapper.selectOne(queryWrapper).getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictcode找parent_id，在根据parent_id找下级节点
        Dict codeDict = this.getDictByDictCode(dictCode);
        if(null == codeDict) return null;
        return this.findChildData(codeDict.getId());
    }

    //将上面方法中共同的部分抽取出来
    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    //判断id下是否有子节点（数据）
    public boolean hasChildren(Long id){
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(dictQueryWrapper);
        return count > 0;  //true代表有，false代表无
    }
}
